package com.dht.xiao.jianye.activity_work_clothes;

import android.os.Build;
import android.os.Bundle;
import android.provider.Settings;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.View;
import android.widget.Toast;

import com.dht.xiao.jianye.R;
import com.dht.xiao.jianye.adapter.BedGetAdapter;
import com.dht.xiao.jianye.adapter.WorkGetAdapter;
import com.dht.xiao.jianye.base.BaseActivity;
import com.dht.xiao.jianye.bean.EmptyCaseBean;
import com.dht.xiao.jianye.bean.EndReadBean;
import com.dht.xiao.jianye.bean.MyCaseBean;
import com.dht.xiao.jianye.bean.SimpleBean;
import com.dht.xiao.jianye.dialog.SureDialog;
import com.dht.xiao.jianye.dialog.SureNewDialog;
import com.dht.xiao.jianye.http.MainHttp;
import com.dht.xiao.jianye.utils.OpenManager;
import com.licheedev.myutils.LogPlus;
import com.trello.rxlifecycle2.android.ActivityEvent;

import java.util.concurrent.TimeUnit;

import butterknife.BindView;
import butterknife.ButterKnife;
import cn.dlc.commonlibrary.okgo.rx.OkObserver;
import cn.dlc.commonlibrary.ui.widget.TitleBar;
import cn.dlc.commonlibrary.utils.ToastUtil;
import io.reactivex.Observable;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;
import io.reactivex.schedulers.Schedulers;

/***
 * 工衣领取
 */
public class WorkGetActivity extends BaseActivity {
    @BindView(R.id.mTitleBar)
    TitleBar mTitleBar;
    @BindView(R.id.mRecyclerView)
    RecyclerView mRecyclerView;
    WorkGetAdapter mRecyclerAdapter;
    String ANDROID_ID;
    OpenManager openManager;

    private String caseNo = "";//空柜编号，为0表示无空柜
    @Override
    protected int getLayoutId() {
        return R.layout.activity_work_get;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_work_get);
        ButterKnife.bind(this);
        mTitleBar.leftExit(this);
        openManager = new OpenManager(this);
        openManager.setCallBack(new OpenManager.OpenCallBack() {
            @Override
            public void onReceiveData(String data,String command, long num, String status) {
                LogPlus.e("", "获取到数据结果--=" + data);


                if (status.equals("00")&& command.equals("82")) {
                    if ((int)num == Integer.parseInt(caseNo)) {
                        ToastUtil.show(getActivity(), num + "号门已打开");
                        initHint();
                    }
                } else if (status.equals("01")&& command.equals("83")){
                    if ((int)num == Integer.parseInt(caseNo)) {
                        stopDisposable();
                        beginRead();
                        ToastUtil.show(getActivity(), num + "号门已关闭");
                    }
                }
            }
            @Override
            public void onInit(Boolean data) {
//                if (data) {
//                    myCase();
//                }else {
//                    ToastUtil.show(getActivity(),  "串口初始化失败，退出领取");
//                    //finish();
//                }
            }
        });
        initRecyclerView();
        getMachineCode();
    }

    private void initRecyclerView() {
        mRecyclerView.setLayoutManager(new LinearLayoutManager(this));
        mRecyclerView.setOverScrollMode(View.OVER_SCROLL_NEVER);
        mRecyclerAdapter = new WorkGetAdapter();
        mRecyclerView.setAdapter(mRecyclerAdapter);
    }
    private void getMachineCode() {
        ANDROID_ID =
                Settings.System.getString(getContentResolver(), Settings.System.ANDROID_ID);
        if (TextUtils.isEmpty(ANDROID_ID)) {
            ANDROID_ID = Build.SERIAL;
        }
        LogPlus.e("ANDROID_ID =" + ANDROID_ID);
       // ANDROID_ID = "909203d36a1a82fb";
        // seriesNum.setText(ANDROID_ID);
        mObservable = Observable.timer(2, TimeUnit.SECONDS)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .compose(bindUntilEvent(ActivityEvent.DESTROY))
                .subscribe(new Consumer<Long>() {
                    @Override
                    public void accept(Long aLong) throws Exception {
                        myCase();
                    }
                });
    }



    private void myCase() {

        MainHttp.get().myCase(ANDROID_ID)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .compose(bindUntilEvent(ActivityEvent.DESTROY))
                .subscribe(new OkObserver<MyCaseBean>() {
                    @Override
                    public void onSuccess(MyCaseBean hotelBean) {
                       // showOneToast(hotelBean.msg);
                        caseNo = hotelBean.data.caseNo;
                        if (!TextUtils.isEmpty(caseNo)&&!caseNo.equals("0")) {
                            openManager.sendOpen(Integer.parseInt(caseNo));
                            //beginRead();
                        }else {
                            ToastUtil.show(getActivity(),"柜号为0，没有可以领取数据");
                        }
                        mRecyclerAdapter.setCaseNo(caseNo);
                        mRecyclerAdapter.setNewData(hotelBean.data.list);
                    }

                    @Override
                    public void onFailure(String message, Throwable tr) {
                        ToastUtil.show(getActivity(), message);
                    }
                });
    }

    private void beginRead() {

        MainHttp.get().beginRead(ANDROID_ID,"1")
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .compose(bindUntilEvent(ActivityEvent.DESTROY))
                .subscribe(new OkObserver<SimpleBean>() {
                    @Override
                    public void onSuccess(SimpleBean hotelBean) {
                       // showOneToast(hotelBean.msg);
                        delaytime();
                    }

                    @Override
                    public void onFailure(String message, Throwable tr) {
                        ToastUtil.show(getActivity(), message);
                    }
                });
    }
    private void delaytime() {
        showWaitingDialog("正在读取",true);
        Observable.timer(5, TimeUnit.SECONDS)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())

                .compose(bindUntilEvent(ActivityEvent.DESTROY))
                .subscribe(new Consumer<Long>() {
                    @Override
                    public void accept(Long aLong) throws Exception {
                        dismissWaitingDialog();
                        endRead(ANDROID_ID,caseNo);
                    }
                });

    }
    private void endRead(String series,String caseNo) {
        MainHttp.get().endRead(series,"2","1",caseNo)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .compose(bindUntilEvent(ActivityEvent.DESTROY))
                .subscribe(new OkObserver<EndReadBean>() {
                    @Override
                    public void onSuccess(EndReadBean hotelBean) {
                        showOneToast(hotelBean.msg);
                        finishHint();
                    }

                    @Override
                    public void onFailure(String message, Throwable tr) {
                        ToastUtil.show(getActivity(), message);
                    }
                });
    }



    private void initHint(){

        SureNewDialog dialog = new SureNewDialog(getActivity(), "领取", getString(R.string.work_get_open));
        dialog.setOnCallBackListener(new SureNewDialog.OnCallBack() {
            @Override
            public void sure() {
                dialog.dismiss();
                start_inquire();
            }
        });
    }
    private void finishHint(){
        Toast.makeText(getActivity(),"已完成领取，系统5秒后退出",Toast.LENGTH_LONG).show();
        Observable.timer(5, TimeUnit.SECONDS)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .compose(bindUntilEvent(ActivityEvent.DESTROY))
                .subscribe(new Consumer<Long>() {
                    @Override
                    public void accept(Long aLong) throws Exception {
                       // dialog.dismiss();
                        finishActivity();
                    }
                });
    }


    private Disposable mObservable;
    private void start_inquire() {
        stopDisposable();
        mObservable = Observable.interval(2,2, TimeUnit.SECONDS)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .compose(bindUntilEvent(ActivityEvent.DESTROY))
                .subscribe(new Consumer<Long>() {
                    @Override
                    public void accept(Long aLong) throws Exception {
                        if (!TextUtils.isEmpty(caseNo)&&!caseNo.equals("0")) {
                            openManager.queryOpen(Integer.parseInt(caseNo));
                        }
                    }
                });
    }

    private void stopDisposable(){
        if (mObservable != null){
            mObservable.dispose();
            mObservable = null;
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        stopDisposable();
        if (openManager != null){
            openManager.onDestroy();
        }
    }
}
